package com.hfjava.demo.util.wxpay;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @describe: java模拟http请求
 * @author: yang
 * @date: 2020/03/09 10:47
 */
@Slf4j
public class HttpUtils {

    /**
     * 发送get请求
     *
     * @param url   地址
     * @param param 参数 name1=value1&name2=value2
     * @return
     */
    public static String sendGetParam(String url, String param) {
        String result = "";
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            //打开url连接
            URLConnection connection = realUrl.openConnection();
            //设置通用请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36");
            //建立实际连接
            connection.connect();
            //获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info(key + "--->" + map.get(key));
            }
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String s;
            StringBuffer stringBuffer = new StringBuffer();
            while ((s = br.readLine()) != null) {
                stringBuffer.append(s);
            }
            result = stringBuffer.toString();
            //关闭输入流
            br.close();
        } catch (MalformedURLException e) {
            log.info("发送get请求异常");
            e.printStackTrace();
        } catch (IOException e) {
            log.info("发送get请求异常");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送post请求
     *
     * @param url   地址
     * @param param 参数 name1=value1&name2=value2
     * @return
     */
    public static String sendPostParam(String url, String param) {
        String result = "";
        try {
            URL realUrl = new URL(url);
            //打开url连接
            URLConnection connection = realUrl.openConnection();
            //设置通用请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36");
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter pw = new PrintWriter(connection.getOutputStream());
            // 发送请求参数
            pw.print(param);
            // flush输出流的缓冲
            pw.flush();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String s;
            StringBuffer stringBuffer = new StringBuffer();
            while ((s = br.readLine()) != null) {
                stringBuffer.append(s);
            }
            result = stringBuffer.toString();
            //关闭输入输出流
            br.close();
            pw.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送post请求
     *
     * @param url  地址
     * @param json 参数json
     * @return
     */
    public static String sendPostJson(String url, String json) {
        String result = "";
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();
            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json, "UTF-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            //第四步：发送HttpPost请求，获取返回值
            result = httpClient.execute(httpPost, responseHandler);
            //关闭流
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
